﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using System.Drawing;

namespace Lottery.Control {
    public class IntegerEdit : TextBox {
        public IntegerEdit() {
            BorderStyle = BorderStyle.FixedSingle;
        }

        /// <summary>
        /// 按回车键的时候，焦点跳转到的控件
        /// </summary>
        public System.Windows.Forms.Control JumpToNext { get; set; }

        protected override void OnKeyPress(KeyPressEventArgs e) {
            // 处理backspace
            bool isOK = e.KeyChar == '\b';
            if (isOK) {
                base.OnKeyPress(e);
                return;
            }

            //处理数字
            isOK = e.KeyChar >= '0' && e.KeyChar <= '9';
            // 处理开头的+ -
            if (e.KeyChar == '+' || e.KeyChar == '-') {
                if (SelectionStart == 0) {
                    if (Text == string.Empty)
                        isOK = true;
                    else if (Text[0] == e.KeyChar)
                        isOK = false; //已经存在 + -
                    else isOK = true;
                }
            }

            if (!isOK) {
                e.KeyChar = '0';
                e.Handled = true;
            }

            base.OnKeyPress(e);
        }

        protected override void OnKeyDown(KeyEventArgs e) {
            if (e.KeyCode == Keys.Return && JumpToNext != null) {
                e.Handled = true;
                JumpToNext.Focus();
            }

            base.OnKeyDown(e);
        }

        private Color oldBackColor;

        protected override void OnEnter(EventArgs e) {
            base.OnEnter(e);

            if (!ReadOnly) {
                oldBackColor = BackColor;
                BackColor = Color.Aqua;
            }
        }

        protected override void OnLeave(EventArgs e) {
            if (!ReadOnly)
                BackColor = oldBackColor;

            base.OnLeave(e);
        }

        protected override void OnEnabledChanged(EventArgs e) {
            base.OnEnabledChanged(e);

            BackColor = Enabled ? SystemColors.Window : SystemColors.ButtonFace;

        }

        public int Value {
            get {
                try {
                    return Convert.ToInt16(Text);
                } catch {
                    return 0;
                };
            }
        }
    }
}
